package com.baidu.dao.impl;
import com.baidu.dao.StudentDao;
import com.baidu.domain.Student;
import com.sun.xml.internal.ws.runtime.config.TubelineFeatureReader;

import java.io.*;
import java.util.ArrayList;

public class StudentDaoImpl implements StudentDao {
    @Override
    public boolean add(Student stu)  {
        //默认添加学生信息失败
        boolean  result=false;
        //创建缓冲字符输出流,并且将数据读取到本地的D://stu.txt 文档当中
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter("D://stu.txt",true));
            bw.write(stu.getUsername()+","+stu.getAge()+","+stu.getScore());
            bw.newLine();
            //正常添加完毕数据后需要将结果修改为成功
            result =true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw !=null)
            {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    @Override
    public  ArrayList<Student> find() {
        //创建集合，将文件夹中的数据存储到集合当中
        ArrayList<Student> list =new ArrayList<>();
        //创建字符缓冲输入流读取数据
        BufferedReader br=null;
        try {
            br = new BufferedReader(new FileReader("D://stu.txt"));
            String len;
            while ((len=br.readLine())!=null)
            {
                //创建学生对象,封装数据
                Student stu = new Student();
                //通过IO流中读取的数据进行分隔
                String[] split = len.split(",");
                stu.setUsername(split[0]);
                stu.setAge(Integer.parseInt(split[1]));
                stu.setScore(Integer.parseInt(split[2]));
                //将学生对象存储到集合当中
                list.add(stu);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br !=null)
            {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return list;
    }
}
